package com.chunxuan.langquan.ui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.RegexUtils;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.LqProvinceBean;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.view.JDCityPicker;
import com.chunxuan.langquan.ui.listener.MyOrientationListener;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class AddAddressActivity extends Base2Activity {

    private AppCompatEditText etReceiver,etMobile,etDetailAddress;
    private TextView tvConfirm;
    private ImageView ivBack;
    private AppCompatTextView tvArea;
    private JDCityPicker mJDCityPicker;
    private List<LqProvinceBean> lqProvinceBeanList=new ArrayList<>();
    private int mProvinceId, mCityId, mAreaId;

    //百度地图-获取定位
    private LocationClient mylocationClient;//定位服务客户对象
    private MylocationListener mylistener;//重写的监听类
    private int count=0;
    private MyOrientationListener myOrientationListener;//方向感应器类对象
    private boolean selectLocation=false;
    private String pro,city,area;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_delivery_address;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        etReceiver=findViewById(R.id.et_receiver);
        etMobile=findViewById(R.id.et_mobile);
        etDetailAddress=findViewById(R.id.et_detail_address);
        tvConfirm=findViewById(R.id.tv_confirm);
        ivBack=findViewById(R.id.iv_back);
        tvArea=findViewById(R.id.et_delivery_address_area_input);
        setOnClickListener(tvConfirm,ivBack,tvArea);

        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
        initLocation();

        getProvList();
    }

    private Disposable getProvList() {
        return APIRetrofit.getDefault().getProvList(Global.HEADER,"")
                .compose(RxUtil.<BaseResult2<List<LqProvinceBean>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<LqProvinceBean>>>() {
                    @Override
                    public void accept(BaseResult2<List<LqProvinceBean>> result2) throws Exception {
                        hideProgress();
                        if(result2.isSuccess()){
                            lqProvinceBeanList=result2.getData();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取省份列表失败");
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_confirm:
                if(TextUtils.isEmpty(etReceiver.getText().toString())){
                    ToastUtils.showShort("请填写收货人");
                    return;
                }
                if(TextUtils.isEmpty(etMobile.getText().toString())){
                    ToastUtils.showShort("请填写手机号");
                    return;
                }
                if(TextUtils.isEmpty(etDetailAddress.getText().toString())){
                    ToastUtils.showShort("请填写详细地址");
                    return;
                }
                if(TextUtils.isEmpty(tvArea.getText().toString())){
                    ToastUtils.showShort("请选择所在地区");
                    return;
                }
                if(!RegexUtils.isMobileExact(etMobile.getText().toString().trim())){
                    ToastUtils.showShort("请填写正确的手机号");
                    return;
                }
                addAddress(etReceiver.getText().toString(),etMobile.getText().toString(),mProvinceId,mCityId,mAreaId,etDetailAddress.getText().toString(),1);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.et_delivery_address_area_input:
                bgAlpha(0.7f);
                mJDCityPicker = new JDCityPicker(AddAddressActivity.this,lqProvinceBeanList, new JDCityPicker.onCitySelect() {
                    @Override
                    public void onSelect(String province, String city, String area,int province_id,int city_id,int area_id) {
                        tvArea.setText(province + "-" + city + "-" + area);
                        mProvinceId=province_id;
                        mCityId=city_id;
                        mAreaId=area_id;
                    }
                },pro,city,area);
                mJDCityPicker.showAtLocation(tvArea, Gravity.BOTTOM, 0, 0);

                mJDCityPicker.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        bgAlpha(1.0f);
                    }
                });
                break;
        }
    }
    private void initLocation() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        mylocationClient = new LocationClient(this);
        mylistener = new MylocationListener();

        //注册监听器
        mylocationClient.registerLocationListener(mylistener);
        //配置定位SDK各配置参数，比如定位模式、定位时间间隔、坐标系类型等
        LocationClientOption mOption = new LocationClientOption();
        //设置坐标类型
        mOption.setCoorType("bd09ll");
        //设置是否需要地址信息，默认为无地址
        mOption.setIsNeedAddress(true);
        //设置是否打开gps进行定位
        mOption.setOpenGps(true);
        //设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        int span = 2000;
        mOption.setScanSpan(span);
        //设置 LocationClientOption
        mylocationClient.setLocOption(mOption);

        myOrientationListener = new MyOrientationListener(AddAddressActivity.this);
    }
    /*
     *定位请求回调接口
     */
    public class MylocationListener implements BDLocationListener {
        //定位请求回调函数,这里面会得到定位信息
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //BDLocation 回调的百度坐标类，内部封装了如经纬度、半径等属性信息
            //MyLocationData 定位数据,定位数据建造器
            /*
             * 可以通过BDLocation配置如下参数
             * 1.accuracy 定位精度
             * 2.latitude 百度纬度坐标
             * 3.longitude 百度经度坐标
             * 4.satellitesNum GPS定位时卫星数目 getSatelliteNumber() gps定位结果时，获取gps锁定用的卫星数
             * 5.speed GPS定位时速度 getSpeed()获取速度，仅gps定位结果时有速度信息，单位公里/小时，默认值0.0f
             * 6.direction GPS定位时方向角度
             * */
            count++;
//            Log.e("==位置==",bdLocation.getProvince()+"-"+bdLocation.getCity()+"-"+bdLocation.getDistrict()+"-"+bdLocation.getStreet());
            if(!TextUtils.isEmpty(bdLocation.getProvince())&&!TextUtils.isEmpty(bdLocation.getCity())&&!TextUtils.isEmpty(bdLocation.getDistrict())){
                Arad.preferences.putString(Config.PROVINCE, bdLocation.getProvince()).flush();
                Arad.preferences.putString(Config.CITY, bdLocation.getCity()).flush();
                Arad.preferences.putString(Config.AREA, bdLocation.getDistrict()).flush();
                if(selectLocation){
                    return;
                }else{
                    pro=bdLocation.getProvince();
                    city=bdLocation.getCity();
                    area=bdLocation.getDistrict();
//                    tvSelectCity.setText(bdLocation.getProvince()+bdLocation.getCity()+bdLocation.getDistrict());
                }
            }
        }
    }
    /*
     *定位服务的生命周期，达到节省
     */
    @Override
    protected void onStart() {
        super.onStart();
        //开启定位，显示位置图标
        if(!mylocationClient.isStarted()){
            mylocationClient.start();
        }
        myOrientationListener.start();
    }
    @Override
    protected void onStop() {
        super.onStop();
        mylocationClient.stop();
        myOrientationListener.stop();
    }

    private Disposable addAddress(String name, String mobile, int mProvinceId, int mCityId, int mAreaId, String address, int is_default) {
        return APIRetrofit.getDefault().addAddress(Global.HEADER,name, mobile, mProvinceId, mCityId,
                mAreaId, address, is_default)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
//                        hideProgress();
                        if(result2.isSuccess()){
                            ToastUtils.showShort(result2.getMsg());
                            finish();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取市区列表失败");
                    }
                });
    }

    //背景变暗
    private void bgAlpha(float f) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = f;
        getWindow().setAttributes(layoutParams);
    }
}
